package kyuu.acshmily.net
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import kyuu.acshmily.events.LoaderEvent;

	[Event(name="loadComplete", type="kyuu.acshmily.events.LoaderEvent")]

	public class VideoInfoLoader extends EventDispatcher
	{
		//private static const infoFile:String = "video.xml";
		// 下载器
		private var loader:URLLoader = null;
		private var piLoader:PartInfoLoader = null;

		// 视频信息
		private var parts:XMLList;
		private var videoInfos:Array;
		private var idx:int;

		public function VideoInfoLoader(){}

		/**
		 * 加载视频信息
		 */
		public function load(vid:String):void{
			videoInfos = new Array();

			try{
				var request:URLRequest = new URLRequest("player/" + vid + ".xml?baka=" + Math.random());
				loader = new URLLoader();
				loader.addEventListener(Event.COMPLETE, completeHandler);
				loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
				loader.load(request);
			}
			catch(err:Error){
				trace(err.message);
			}
		}

		/**
		 * 释放资源
		 */
		public function close():void{
			if(piLoader != null){
				piLoader.removeEventListener(LoaderEvent.LOAD_COMPLETE, partCompleteHandler);
				piLoader.close();

				piLoader = null;
			}
			if(loader != null){
				loader.removeEventListener(Event.COMPLETE, completeHandler);
				loader.removeEventListener(IOErrorEvent.IO_ERROR, errorHandler);
				loader.close();

				loader = null;
			}
		}

		/**
		 * 加载完成事件处理函数
		 */
		private function completeHandler(e:Event):void{
			if(e.type != Event.COMPLETE) return;

			// 释放资源移动到close方法中
			//loader.removeEventListener(Event.COMPLETE, completeHandler);
			//loader.removeEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			var videoXML:XML = new XML(loader.data);
			loader.data = null;
			//loader.close();

			// 获取part节点
			parts = videoXML.part;
			piLoader = new PartInfoLoader();
			piLoader.addEventListener(LoaderEvent.LOAD_COMPLETE, partCompleteHandler);
			idx = 0;
			piLoader.loadInfo(parts[idx++]);
		}

		/**
		 * 一个信息加载完成时
		 */
		private function partCompleteHandler(e:LoaderEvent):void{
			var vis:Array = e.data as Array;
			videoInfos = videoInfos.concat(vis);

			if(idx==parts.length()){
				// 释放资源移动到close方法中
				//piLoader.removeEventListener(LoaderEvent.LOAD_COMPLETE, partCompleteHandler);
				//piLoader.close();

				var le:LoaderEvent = new LoaderEvent(LoaderEvent.LOAD_COMPLETE, false, false, videoInfos);
				dispatchEvent(le);
			}
			else{
				piLoader.loadInfo(parts[idx++]);
			}
		}

		/**
		 * 错误事件处理函数
		 */
		private function errorHandler(e:IOErrorEvent):void{
			trace(e.text);
			// 释放资源移动到close方法中
			//loader.removeEventListener(Event.COMPLETE, completeHandler);
			//loader.removeEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			//loader.close();
		}
	}
}